<script setup lang="ts">
import { EnterpriseAddAPI, EnterpriseIndustryAPI, getEnterpriseDetailAPI, UploadAPI, uploadEnterpriseAPI } from '@/apis/enterprise';
import type { EnterpriseParams, Industry } from '@/types/enterprise';
import { CircleCheck, Upload } from '@element-plus/icons-vue';
import { ElMessage, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 根据接口文档定义字段，用于表单双向绑定
const addForm = ref<EnterpriseParams>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode:undefined, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: '' // 营业执照id
}) 

const industryList = ref<Industry[]>([])
const getIndustry = async () => {
  const res = await EnterpriseIndustryAPI()
  // console.log(res)
  industryList.value = res.data
}
getIndustry()

const addRules = ref<FormRules<EnterpriseParams>>({
  name: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  legalPerson: [
    { required: true, message: '请输入法人', trigger: 'blur' }
  ],
  registeredAddress: [
    { required: true, message: '请输入注册地址', trigger: 'blur' }
  ],
  industryCode: [
    { required: true, message: '请选择行业', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '请输入企业联系人', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
})

const ruleForm = ref<FormInstance>()
// 上传营业执照
const onUploadRequest = async (Options: UploadRequestOptions) => {
  // console.log(Options)
  const fd = new FormData()
  fd.append('file', Options.file)
  fd.append('type', 'businessLicense')
  const res = await UploadAPI(fd)
  // console.log(res.data.url)
  addForm.value.businessLicenseUrl = res.data.url
  addForm.value.businessLicenseId = res.data.id
  // 主动触发校验
  ruleForm.value?.validateField('businessLicenseUrl')
  // 检查上传结果,并return存储到response属性中
  return res.data.url
}

// 删除上传的钩子
const BeforeRemove = () => {
  addForm.value.businessLicenseUrl = ''
  addForm.value.businessLicenseId = ''
  ruleForm.value?.validateField('businessLicenseUrl')
}

// 上传前
const beforeUpload = (rawFile:UploadRawFile) => {
  if (rawFile.size > 5 * 1024 * 1024) {
    ElMessage.error('上传图片不能大于5M')
    return false
  } else if (['image/jpeg', 'image/png'].includes(rawFile.type) === false) {
    ElMessage.error('上传图片格式不正确')
    return false
  }
  return true
}

const fileList = ref<UploadUserFile[]>([])

const router = useRouter()
const submitLoading = ref(false)

// 表单提交
const onsubmit = async () => {
  try {
    await ruleForm.value?.validate()
    // 把按钮设置为加载状态(禁用提交,避免重复提交)
    submitLoading.value = true
    if (route.params.id) {
      await EnterpriseAddAPI(addForm.value)
    } else {
      await uploadEnterpriseAPI(addForm.value)
    }
    ElMessage.success(route.params.id ? '编辑成功' : '添加成功')
    router.back()
  } catch {
    submitLoading.value = false
  }
}
// 表单重置
const onReset = () => {
  ruleForm.value?.resetFields()
}

const route = useRoute()
// 编辑回显
const getEnterpriseDetail = async () => {
  const res = await getEnterpriseDetailAPI(route.params.id as string)
  // 解构化数据
  const { name, legalPerson, registeredAddress, industryCode, contactNumber, contact, businessLicenseUrl, businessLicenseId } = res.data
  addForm.value = { 
    name, 
    legalPerson, 
    registeredAddress, 
    industryCode, 
    contactNumber, 
    contact, 
    businessLicenseUrl, 
    businessLicenseId:businessLicenseId.toString() 
  }
  // 更新文件列表以显示已上传的营业执照
  if (businessLicenseUrl) {
    fileList.value = [
      { name: '营业执照', url: businessLicenseUrl}
    ]
  }
}
if (route.params.id) {
  getEnterpriseDetail()
}
</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header content="添加企业" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :rules="addRules" :model="addForm">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" >
                <el-option v-for="item in industryList" :key="item.industryCode" :label="item.industryName" :value="item.industryCode"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" :maxlength="11"/>
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <el-upload 
              list-type="picture"
              :http-request="onUploadRequest" 
              @remove="BeforeRemove"
              :limit="1"
              accept=".png,.jpg,.jpeg,.gif,.bmp"
              :before-upload="beforeUpload"
              v-model:file-list="fileList"
              >
                <el-button type="primary" :icon="Upload" v-if="fileList.length === 0">上传文件</el-button>
                <el-button type="success" disabled :icon="CircleCheck" v-else>已上传</el-button>
                <template #tip>
                  <div :style="{ color: '#909399' , fontSize: '12px' }">
                    支持扩展名：.png .jpg .jpeg .gif .bmp 文件大小不得超过5M
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        {{ addForm }}
      </div>
      {{ fileList }}
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onsubmit" :loading="submitLoading">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>